package com.linxi.handy.component.listener;

import com.linxi.handy.Application;
import com.linxi.handy.component.control.HomeControl;
import com.linxi.handy.component.view.Tableview;

import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

import static com.linxi.handy.component.listener.DatabaseList.top;
import static com.linxi.handy.component.listener.DatabaseList.tree;

class TreeListener implements MouseListener {

    int clickCount = 2;

    @Override
    public void mouseClicked(MouseEvent arg0) {
        //响应左键事件
        if (arg0.getButton() == MouseEvent.BUTTON1) {
            //响应双击事件
            if (arg0.getClickCount() == clickCount) {
                TreeNode s = (TreeNode) tree.getLastSelectedPathComponent();
                if (s == null) {
                    return;
                }
                TreePath path = tree.getPathForLocation(arg0.getX(), arg0.getY());
                //可以确保点在节点上才触发事件
                if (path == null) {
                    return;
                }
                //为叶子结点（表）打开管理页面
                if (s.getParent() != top) {
                    String pname = s.getParent().toString();
                    String sname = s.toString();

                    int i = HomeControl.ft.indexOfTab(pname + "." + sname);
                    //打开过的不重复打开
                    if (i > -1) {
                        HomeControl.ft.setSelectedIndex(i);
                    } else {
                        if (Tableview.conn == null) {
                            new Application().setConnection();
                        }
                        HomeControl.ft.add(new Tableview(pname, sname), pname + "." + sname);
                        i = HomeControl.ft.indexOfTab(pname + "." + sname);
                        HomeControl.ft.setSelectedIndex(i);
                    }
                }
            }
        }
    }

    @Override
    public void mouseEntered(MouseEvent arg0) {

    }

    @Override
    public void mouseExited(MouseEvent arg0) {

    }

    @Override
    public void mousePressed(MouseEvent arg0) {

    }

    @Override
    public void mouseReleased(MouseEvent arg0) {

    }
}